$(function() {
		var $tabs = $("#tabs").tabs({

			// template for the tab
			tabTemplate: "<li><a href='#{href}'>#{label}</a>\
                                 <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",

            // whatt to do when a tab is added
			add: function(event, ui) {
			 	$tabs.tabs('select', '#' + ui.panel.id);

		    }
		});

		// variable to hold number of static tabs
		var categoryNumber = 1;

		function addCategory(categoryName) {
			var category = "#category-" + (++categoryNumber);
            $tabs.tabs("add", category, categoryName);
			$(category).html('<div>\
								<button id="addToDoThing">Add ToDO</button>\
								<div class="accordion">\
        						</div>\
        					 </div>')
			.configureToDoList();

		}

		// remove the tab from the panel
		$('#tabs').on('click', 'li span.ui-icon-close', function() {
			$tabs.tabs('remove', $(this).closest('li').index());
		});

		var addNewCategory = $("#addNewCategory").dialog({
				resizable: false,
			    modal: true,	
    			autoOpen: false,
    			buttons: {

      				// creates a button to handle adding a new tab.
        			"Add new category": function() {

        				var nameValue = $('#categoryName').val();

        				if(nameValue == '') {
        					alert('Name field cannot be empty!');
        				} else {

	            			addCategory(nameValue);

	          				// Close the dialog
	            			$(this).dialog('close');

	            			// Clear the value on the form field in the dialog.
	            			$("#categoryName").val('');
        				}
       				 },

        			// creates a button to cancel the dialog.
        			"Cancel": function() {

		            	// Close the dialog
		           		 $(this).dialog("close");

		            	// Clear any values that may of been entered.
		            	$("#categoryName").val("");
		        	}
   			 	}		
		});

		// adding new tabs
		$('button#addCategory').on('click', function() {
			addNewCategory.dialog('open');
		}).button();

		/*Adding todo elements*/

		// Setup a function that is easy to reuse.
		$.fn.configureToDoList = function() {
		    // return the jQuery object so that we can continue chaining
		    return this.find(".accordion")

		    // call the refreshAccordion method which tearsdown and rebuilds the todo
		    // list as an accordion.
		    .refreshAccordion()

		    // make the todo list sortable.
		    .sortable({

		        // constrain movement to the y axis only
		        axis: "y",

		        // define which element will be the handle when sorting.
		        handle: "h3",

		        stop: function() {
		            stop = true;
		        },

		        // Don't sort elements with class ui-state-disabled.
		        cancel: ".ui-state-disabled"
		    })

		    // return the set of matched elements to it's previous state.
		    .end().find("button")

		    // set the element with class 'button' as a button widget.
		    .button();
		};


		$.fn.refreshAccordion = function() {
		    // return the jQuery object so that we can continue chaining
		    return this

		    // // call the destroy method which tears down the accordion.
		    // .accordion('destroy')

		    // set our jQuery object back into an accordion
		    .accordion({
		        active: false,  
		        autoHeight: false, 
		        collapsible: true,
		        header: "> div > h3"
		    })

		    // calling the refresh method for sortable allows the new item to be sortable.
		    .sortable('refresh');
		};

		// accordion to do list
		// stop is a variable we will use to keep track if any item is moving during a sort.
		var stop = false;

		// configure static todo elements
		$('.ui-tabs-panel').configureToDoList();

		$('.accordion h3').on('click', function(event) {

			    // if the item is moving disable the click event for the accordion widget.
			    if (stop) {

			        // keeps other handlers from being executed and prevents the event from 
			        // bubbling up the DOM tree.
			        event.stopImmediatePropagation();

			        // this will prevent the default action of the event from being triggered.
			        event.preventDefault();

			        // reset the stop variable 
			        stop = false;
			    }
		})
		.closest('div')
		.css('margin-bottom', '10px')
		.end()
		.hover(
			function() {
			$(this).append('<span class=\'ui-icon ui-icon-closethick\'>Remove ToDo</span>');
		}, function() {
			$(this).find('span.ui-icon-closethick').remove();
		});

		// remove the ToDo from the accordion
		$('.accordion h3').on('click', 'span.ui-icon-closethick', function(event) {
			event.stopImmediatePropagation();
			$(this).closest('div').fadeOut(function() {
				$(this).remove();
				$('.accordion').refreshAccordion();
			});
		});


});